package org.example.chat.controller;

import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.chat.aop.annotation.Log;
import org.example.chat.aop.annotation.SaveLog;
import org.example.chat.api.CommonResult;
import org.example.chat.api.Constant;
import org.example.chat.entity.User;
import org.example.chat.security.components.utils.JWTUtils;
import org.example.chat.security.config.SecurityConfigProperties;
import org.example.chat.security.entity.LoginUser;
import org.example.chat.service.IUserService;
import org.example.chat.vo.LoginVo;
import org.example.chat.vo.RegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * @author cheval
 */
@Slf4j
@RestController
@RequestMapping("/security")
public class LoginController extends BaseController {
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private IUserService userService;

    /**
     * 登录
     * @param loginVo
     * @return
     */
    @Log
    @SaveLog(logType = Constant.LOG_TYPE_USER_LOGIN, content = "用户登录")
    @PostMapping(value = "/login")
    public CommonResult<String> login(@Validated @RequestBody LoginVo loginVo) {
        Authentication in = new UsernamePasswordAuthenticationToken(loginVo.getUsername(),loginVo.getPassword());
        Authentication out = authenticationManager.authenticate(in);
        // 全局上下文设置登录状态
        SecurityContextHolder.getContext().setAuthentication(out);
        // 获取token 载荷
        LoginUser payload = (LoginUser)out.getPrincipal();
        // 生成token并返回
        String token = jwtUtils.generateToken(payload);
        return CommonResult.successNoMessage(token);
    }

    /**
     * 检查账号是否存在
     * @param username
     * @return
     */
    @GetMapping("/checkAccountIsExist")
    public CommonResult<Boolean> checkAccountIsExist(String username) {
        User user = userService.queryUserByUsername(username);
        if (user != null) {
            return CommonResult.success(true);
        }
        return CommonResult.success(false);
    }


    /**
     * 注册
     * @param registerVo
     * @return
     */
    @PostMapping("/register")
    public CommonResult register(@Validated @RequestBody RegisterVo registerVo) {
        int statusCode = userService.addUser(registerVo);
        if (statusCode == 1) {
            return CommonResult.fail("注册失败");
        }

        if (statusCode == 2) {
            return CommonResult.fail("验证码错误");
        }

        if (statusCode == 3) {
            return CommonResult.fail("验证码已过期");
        }
        return CommonResult.success("注册成功");
    }

    /**
     * 获取登录用户详细信息
     * @return
     */
    @GetMapping("/obtainLoginUserInfo")
    public CommonResult<User> obtainLoginUserInfo() {
        LoginUser loginUserInfo = getLoginUserInfo();
        User userinfo = userService.queryUserByUsername(loginUserInfo.getUsername());
        userinfo.setPassword(null);
        return CommonResult.success(userinfo);
    }

    /**
     * 获取验证码
     * @return
     */
    @Log
    @GetMapping("/getCaptcha")
    public CommonResult<Map<String, String>> getCaptcha() {
        ArithmeticCaptcha arithmeticCaptcha = new ArithmeticCaptcha(120, 40, 2);
        // 算数验证码计算结果
        String arithmeticResult = arithmeticCaptcha.text().toLowerCase();
        // base64格式的验证码
        String captcha = arithmeticCaptcha.toBase64();
        // 1. 将验证码计算结果存入redis
        String key = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(key, arithmeticResult, securityConfigProperties.getCaptchaTimeout(),TimeUnit.SECONDS);
        // 2. 组装返回数距
        Map<String, String> res = new HashMap<>();
        res.put("captchaKey", key);
        res.put("captcha", captcha);
        return CommonResult.success(res);
    }
}
